import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author malguy-wang sir
 * @create ---
 */
public class myCopyOnWriteArrayList<E> {
    public myCopyOnWriteArrayList() {
        setArray(new Object[0]);//初始化
    }

    private Object[] array;//只能通过get和set方法访问

    public Object[] getArray() {
        return array;
    }

    public void setArray(Object[] array) {
        this.array = array;
    }

    //获取长度
    public int size() {
        return getArray().length;
    }

    public E get(int index) {
        return (E) getArray()[index];
    }

    public boolean add(E value) {
        //底层使用lock锁
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            Object[] temp = getArray();
            int len = temp.length;
            //复制过来一份
            Object[] newTemp = Arrays.copyOf(temp, len + 1);
            //添加
            newTemp[len] = value;
            //合并
            setArray(newTemp);
            return true;
        } finally {
            lock.unlock();
        }
    }

}
